#include <stdio.h>
#include <stdlib.h>

void my_itoa (char *str, int x)
{
    int i, j;

    i = j = 0;
    
    if (x == 0) {
        str[0] = '0';
        return;
    } else if (x < 0) {
        x = -x;
        str[i++] = '-';
        j = i;
    } 

    for (; x > 0; x /= 10, i++) {
        str[i] = x % 10 + '0';
    }

    i--;

    for (; j < i; j++, i--) {
        str[j] = str[j] + str[i];
        str[i] = str[j] - str[i];
        str[j] = str[j] - str[i];
    }
}

int my_atoi (const char *nptr)
{
    int dec = 0;
    int sign = 1;
    const char *p = nptr;

    sign = (*p == '-') ?  -1 : 1;
    
    if ((*p == '-') || (*p == '+')) {
        p++;
    }

    while (*p) {
        if (isdigit(*p)) {
            dec = dec * 10 + *p - '0';
        }
        p++;
    }

    return (sign * dec);
}

int hexstr_to_dec (const char *hex)
{
    int dec = 0, n;
    const char *p = hex;

    while (*p) {
        if ('a' <= *p && *p <= 'f') {
            n = *p - 'a' + 10;            
        } else if ('A' <= *p && *p <= 'F') {
            n = *p - 'A' + 10;
        } else if ('0' <= *p && *p <= '9') {
            n = *p - '0';
        } else {
            break;
        }
        dec = dec * 16 + n;
        p++;
    }

    return dec;
}

int main(int argc, char *argv[])
{
    char str[32] = { 0 };
    int x;
    
    printf("0xab34 =%d\n", hexstr_to_dec("aB34"));

    printf("1234=%d, -4=%d, 12k3=%d\n", my_atoi("1234"), my_atoi("-4"), my_atoi("12k3"));

    x = 3456;
    memset(str, 0, sizeof(str));
    my_itoa(str, x);
    printf("%d = %s\n", x, str);

    x = -45678;
    memset(str, 0, sizeof(str));
    my_itoa(str, x);
    printf("%d = %s\n", x, str);
    
    x = 0x0;
    memset(str, 0, sizeof(str));
    my_itoa(str, x);
    printf("%d = %s\n", x, str);
        
    return 0;
}
